import util from '@/libs/util.js'
import md5 from 'js-md5'
import { AccountLogin, GetLoginInfo } from '@api/user'

export default {
  namespaced: true,
  state: {
    token: '',
    name: '',
    avatar: '',
    roles: [],
    menus: [],
    buttons: [],
    columns: []
  },
  getters: {
    token() {
      return util.cookies.get('ticket')
    },
    name(state) {
      return state.name
    },
    avatar(state) {
      return state.avatar
    },
    roles(state) {
      return state.roles
    },
    menus(state) {
      return state.menus
    },
    buttons(state) {
      return state.buttons
    },
    columns(state) {
      return state.columns
    }
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons
    },
    SET_COLUMNS: (state, columns) => {
      state.columns = columns
    }
  },
  actions: {
    /**
     * @description 登录
     * @param {Object} param context
     * @param {Object} param vm {Object} vue 实例
     * @param {Object} param username {String} 用户账号
     * @param {Object} param password {String} 密码
     * @param {Object} param route {Object} 登录成功后定向的路由对象 任何 vue-router 支持的格式
     */
    login({ dispatch }, {
      account,
      pwd
    }) {
      return new Promise((resolve, reject) => {
        // 开始请求登录接口
        pwd = md5(pwd)
        AccountLogin({
          account,
          pwd
        }).then(async res => {
          if (res.status === 200) {
            util.cookies.set('ticket', res.data.ticket)
            util.cookies.set('userName', res.data.userName)
            util.cookies.set('roleName', res.data.roleName)
            await dispatch('getInfo').then(s => {
              if (s.status === 200) {
                res = s
              }
            })
            await dispatch('load')
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    getInfo({ dispatch, commit }) {
      const result = new Promise((resolve, reject) => {
        GetLoginInfo().then(async res => {
          const data = res.data
          // 设置 vuex 用户信息
          await dispatch('d2admin/user/set', {
            name: data.userName,
            avatar: data.headImg
          }, { root: true })
          // 用户登录后从持久化数据加载一系列的设置
          await dispatch('load')
          commit('SET_ROLES', data.userRole)
          commit('SET_MENUS', data.userMenu)
          commit('SET_BUTTONS', data.userButton)
          commit('SET_COLUMNS', data.userColumn)
          commit('SET_NAME', data.userName)
          commit('SET_AVATAR', data.headImg)
          await resolve(res)
        }).catch(error => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_MENUS', [])
          commit('SET_BUTTONS', [])
          commit('SET_COLUMNS', [])
          commit('SET_NAME', '')
          commit('SET_AVATAR', '')
          util.cookies.remove('ticket')
          util.cookies.remove('userName')
          util.cookies.remove('roleName')
          reject(error)
        })
      })
      return result
    },
    /**
     * @description 注销用户并返回登录页面
     * @param {Object} param context
     * @param {Object} param vm {Object} vue 实例
     * @param {Object} param confirm {Boolean} 是否需要确认
     */
    logout({ commit }, { vm, confirm = false }) {
      /**
       * @description 注销
       */
      function logout() {
        // 删除cookie
        util.cookies.remove('ticket')
        util.cookies.remove('userName')
        util.cookies.remove('roleName')
        // 跳转路由
        vm.$router.push({
          name: 'login'
        })
      }
      // 判断是否需要确认
      if (confirm) {
        commit('d2admin/gray/set', true, { root: true })
        vm.$confirm('注销当前账户吗?  打开的标签页和用户设置将会被保存。', '确认操作', {
          confirmButtonText: '确定注销',
          cancelButtonText: '放弃',
          type: 'warning'
        })
          .then(() => {
            commit('d2admin/gray/set', false, { root: true })
            logout()
          })
          .catch(() => {
            commit('d2admin/gray/set', false, { root: true })
            vm.$message('放弃注销用户')
          })
      } else {
        logout()
      }
    },
    /**
     * @description 用户登录后从持久化数据加载一系列的设置
     * @param {Object} state vuex state
     */
    load({ dispatch }) {
      return new Promise(async resolve => {
        // DB -> store 加载用户名
        await dispatch('d2admin/user/load', null, { root: true })
        // DB -> store 加载主题
        await dispatch('d2admin/theme/load', null, { root: true })
        // DB -> store 加载页面过渡效果设置
        await dispatch('d2admin/transition/load', null, { root: true })
        // DB -> store 持久化数据加载上次退出时的多页列表
        await dispatch('d2admin/page/openedLoad', null, { root: true })
        // DB -> store 持久化数据加载侧边栏折叠状态
        await dispatch('d2admin/menu/asideCollapseLoad', null, { root: true })
        // DB -> store 持久化数据加载全局尺寸
        await dispatch('d2admin/size/load', null, { root: true })
        // end
        resolve()
      })
    }
  }
}
